package com.cmii.sjw.department.control.jsc.handler;

import cn.dev33.satoken.exception.NotPermissionException;
import com.cmii.sjw.department.control.jsc.constant.MessageConstant;
import com.cmii.sjw.department.control.jsc.exception.BaseException;
import com.cmii.sjw.department.control.jsc.util.Result;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Map;


/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
//@ControllerAdvice
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(BaseException.class)
    public ResponseEntity<Result<?>> exceptionHandler(BaseException ex) {
        log.error("业务异常信息：{}", ex.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .body(Result.error(ex.getErrorCode(), ex.getMessage()));
    }

    @ExceptionHandler({NullPointerException.class, IllegalArgumentException.class})
    public Result<?> handleCommonExceptions(RuntimeException ex) {
        log.error("运行时异常信息：{}", ex.getMessage());
        return Result.error("参数错误，请检查输入");
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleGeneralException(Exception ex) {
        log.error("未知异常信息：{}", ex.getMessage(), ex);
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<?> handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        if (message.contains("Duplicate entry")) {
            String[] split = message.split(" ");
            String username = split[2];
            String errMsg = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(errMsg);
        } else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

    @ExceptionHandler(NotPermissionException.class)
    public ResponseEntity<?> handlePermissionException(NotPermissionException e) {
        return ResponseEntity.status(403).body(Map.of(
                "code", 403,
                "data", "",
                "msg", "权限不足: " + e.getPermission()
        ));
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<?> handleJsonParseError(HttpMessageNotReadableException ex) {
        String message = "请求参数格式错误";

        if (ex.getCause() instanceof InvalidFormatException) {
            InvalidFormatException ife = (InvalidFormatException) ex.getCause();
            StringBuilder pathBuilder = new StringBuilder();

            // 遍历所有路径引用
            for (JsonMappingException.Reference ref : ife.getPath()) {
                if (ref.getFieldName() != null) {
                    pathBuilder.append(".").append(ref.getFieldName());
                } else if (ref.getIndex() >= 0) {
                    pathBuilder.append("[").append(ref.getIndex()).append("]");
                }
            }

            String errorPath = pathBuilder.length() > 0
                    ? pathBuilder.substring(1)  // 去除首个点号
                    : "unknown_field";

            message = String.format("字段 %s 类型不匹配，预期为 %s",
                    errorPath,
                    ife.getTargetType().getSimpleName());
        }

        log.error("参数反序列化失败: {}", message);
        return ResponseEntity.badRequest().body(Map.of(
                "code", 500,
                "data", "",
                "msg", message));
    }
}
